package com.lingnan.controller;

import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.nacos.api.model.v2.Result;
import com.jisu.vo.AiQuestionVo;
import com.lingnan.common.ChatSessionManager;
import com.lingnan.utils.AiUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@CrossOrigin(origins = "*")
@Slf4j
@RequiredArgsConstructor

public class AiController {
    private final AiUtils aiUtils;

    // 用户管理器
    private final ChatSessionManager sessionManager;

    /**
     * 初始化用户聊天会话：将系统prompt给到AI
     * @param userId 用户userId
     * @return 初始化状态
     */
    @GetMapping("/start/{userId}")
    public Result startChatSession(@PathVariable("userId") String userId) {
        log.info("用户{}开始聊天", userId);
        return Result.success(sessionManager.createSession(userId));
    }

    @PostMapping("/send")
    public ResponseEntity<String> chat(@RequestBody AiQuestionVo aiQuestionVo) {
        log.info("收到用户{}问题: {}",aiQuestionVo.getUserId() , aiQuestionVo.getQuestion());
        try {
            GenerationResult result = aiUtils.continuousChat(aiQuestionVo.getUserId(), aiQuestionVo.getQuestion());
            log.info("AI响应: {}", result.getOutput());
            String response = result.getOutput().getChoices().get(0).getMessage().getContent();
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("对话异常: {}", e.getMessage());
            return ResponseEntity.status(500).body("服务异常: " + e.getMessage());
        }
    }
}
